﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FormView.UI.ChoiceView
{
	public class SingleChoiceWindow : FormWindowBase
	{
		private int mCurrentSelectIndex = -1;

		public SingleChoiceWindow(string @namespace) : base(@namespace) {}

		public void LoadView(string[] items, int selectIndex = -1)
		{
			if (selectIndex >= items.Length)
			{
				throw new ArgumentException("Choice View的默认选项，不可大于选项的最大索引");
			}
			mCurrentSelectIndex = selectIndex;
			for (var i = 0; i < items.Length; i++)
			{
				string item = items[i];
				if (selectIndex >= 0)
				{
					AddControl(InitSingleChoiceView(item, selectIndex, i));
				}
				else
				{
					AddControl(InitButtonChoiceView(item, i));
				}
			}
		}

		private UIElement InitSingleChoiceView(string item, int selectIndex, int curIdx)
		{
			RadioButton radioButton = new RadioButton()
			{
				Style = Resources["RadioButtonStyle"] as Style,
				Content = item,
				IsChecked = selectIndex == curIdx,
				Foreground = DefaultForeColor,
				Background = new SolidColorBrush(ParseColorStr("#99000000")),
				FontSize = 14,
				Padding = new Thickness(10, 5, 10, 5),
				VerticalAlignment = VerticalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center,
				BorderThickness = new Thickness(0, 1, 0, 0),
				Tag = curIdx
			};
			radioButton.Click += (sender, args) =>
			{
				mCurrentSelectIndex = (int)radioButton.Tag;
				Close();
			};
			return radioButton;
		}

		private UIElement InitButtonChoiceView(string item, int curIdx)
		{
			Button btn = new Button()
			{
				Content = item,
				Foreground = DefaultForeColor,
				Background = new SolidColorBrush(ParseColorStr("#99000000")),
				FontSize = 14,
				Padding = new Thickness(10, 5, 10, 5),
				VerticalAlignment = VerticalAlignment.Center,
				VerticalContentAlignment = VerticalAlignment.Center,
				HorizontalContentAlignment = HorizontalAlignment.Left,
				BorderThickness = new Thickness(0,1,0,0),
				Tag = curIdx
			};
			btn.Click += (sender, args) =>
			{
				mCurrentSelectIndex = (int)btn.Tag;
				Close();
			};
			return btn;
		}

		protected override FormResult GetFormResult()
		{
			return new FormResult(mCurrentSelectIndex);
		}

		protected override FormResult OnUserCloseWinGetResult()
		{
			return new FormResult(null);
		}
	}
}
